package com.firewolf.vue.controller;

import com.firewolf.vue.params.UserParam;
import com.firewolf.vue.pojo.User;
import com.firewolf.vue.service.UserService;
import com.firewolf.vue.util.PoiUtil;
import com.firewolf.vue.vo.PageVo;
import com.firewolf.vue.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/2/28
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 显示用户列表
     *
     * @param param
     * @return
     */
    @GetMapping("/list")
    public PageVo<User> userlist(UserParam param) {
        return userService.findUserList(param);
    }


    /**
     * 新增后者修改用户
     *
     * @param u
     * @return
     */
    @PostMapping
    public ResponseVO saveUser(User u) {
        //过来的密码要加密
        try {
            userService.save(u);
        } catch (Exception e) {
            return ResponseVO.error("保存用户失败");
        }
        return ResponseVO.ok("保存用户成功");
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> export() throws Exception {

        HttpStatus status = HttpStatus.OK;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息.xls", "utf-8"));

        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        List<User> data = userService.findAllUsers();
        PoiUtil.exportExecl(bao, Arrays.asList("ID", "用户名", "邮箱", "手机号", "角色"), Arrays.asList("id", "name", "email", "mobile", "roles"), data);

        byte[] body = bao.toByteArray();//把输出流的数据转成字节数组
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, status);
        return responseEntity;

    }
}
